package com.xyzwps.ewa.common

import io.ktor.http.*
import io.ktor.server.request.*
import kotlinx.serialization.Serializable

@Serializable
data class Page(val pageNo: Int, val pageSize: Int) {
    companion object {
        fun from(req: ApplicationRequest): Page = Page(
            pageNo = pageNo(req.queryParameters),
            pageSize = pageSize(req.queryParameters),
        )

        private fun pageNo(params: Parameters): Int {
            val pageNoText = params["pageNo"]
            if (pageNoText.isNullOrEmpty()) {
                return 1;
            }
            val pageNo = try {
                pageNoText.trim().toInt()
            } catch (e: Exception) {
                throw ServerException("pageNo is invalid", HttpStatusCode.BadRequest)
            }

            if (pageNo <= 0) {
                throw ServerException("pageNo should be greater than 0", HttpStatusCode.BadRequest)
            }
            return pageNo
        }

        private fun pageSize(params: Parameters): Int {
            val pageSizeText = params["pageSize"]
            if (pageSizeText.isNullOrEmpty()) {
                return 10;
            }

            val pageSize = try {
                pageSizeText.trim().toInt()
            } catch (e: Exception) {
                throw ServerException("pageSize is invalid", HttpStatusCode.BadRequest)
            }
            if (pageSize <= 0) {
                throw ServerException("pageSize should be greater than 0", HttpStatusCode.BadRequest)
            }
            if (pageSize > 100) {
                throw ServerException("pageSize cannot be greater than 100", HttpStatusCode.BadRequest)
            }
            return pageSize
        }
    }
}
